<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!-- 添加分类区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 分类列表区域 -->
      <!-- 表格 -->
      <!-- columns 表格各列的配置 -->
      <!-- selection-type 是否为多选类型表格 -->
      <!-- expand-type 是否为展开行类型-->
      <!-- 数据表格区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :expand-type="false"
        :show-row-hover="true"
        show-index
      >
        <!-- 是否有效 -->
        <template slot="isValid" slot-scope="scope">
          <i
            v-if="scope.row.cat_deleted === false"
            class="el-icon-success"
            style="color: lightgreen; font-size: 22px"
          ></i>
          <i
            v-else
            class="el-icon-error"
            style="color: red; font-size: 22px"
          ></i>
        </template>

        <!-- 级别 -->
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" type="primary">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="button" slot-scope="scope">
          <!-- {{scope.row}} -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            @click="showEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="open(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageNumChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateVisible"
      width="50%"
      @close="handleAddClose"
    >
      <el-form
        ref="addcateForm"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedCateIds"
            :options="parentCateList"
            :props="parentCateProps"
            @change="handleChange"
            clearable
            props.checkStrictly
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 脚部两个按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑类别的对话框 -->
    <el-dialog
      title="编辑类别"
      :visible.sync="editCateVisible"
      width="50%"
      @close="handleEditClose"
    >
      <!-- 对话框的主要内容 -->
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 脚部两个按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCatesInfo(editForm.cat_id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList();
  },
  data() {
    return {
      cateList: [],
      total: 0,
      queryInfo: {
        type: 3,
        pagenum: 1, // 页码
        pagesize: 5, // 每页条数
      },
      // 为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 表示当前列定义为模板列
          type: "template",
          // 定义模板名称
          template: "isValid",
        },
        {
          label: "级别",
          type: "template",
          template: "level",
        },
        {
          label: "操作",
          type: "template",
          template: "button",
        },
      ],

      // 控制添加分类对话框的显示和隐藏
      addCateVisible: false,
      // 添加分类表单
      addForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      // 添加分类表单验证规则
      addFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
      },
      // 父级分类列表
      parentCateList: [],
      //选择的类型id数组
      selectedCateIds: [],
      // 父分类级联选择器的配置对象
      parentCateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 控制编辑分类对话框的显示和隐藏
      editCateVisible: false,
      // 添加分类表单
      editForm: {
        cat_name: "",
      },
      // 添加分类表单验证规则
      editFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 每页条数改变了
    pageSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    // 当前页码改变了 , newPageNum 就是改变后的新页码
    pageNumChange(newPageNum) {
      // 修改模型数据 queryInfo.pagenum
      this.queryInfo.pagenum = newPageNum;
      // 重新获取数据
      this.getCateList();
    },

    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }

      this.cateList = res.data.result;
      this.total = res.data.total;

      // console.log(this.total);
      // console.log(res.data);
    },

    // 打开添加分类对话框
    async showAddCateDialog() {
      // 获取父分类数据
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.parentCateList = res.data;
      this.addCateVisible = true;
    },
    // 关闭添加分类对话框
    handleAddClose() {
      this.$refs.addcateForm.resetFields();
      this.addCateVisible = false;
    },
    // 添加分类确认
    async addCate() {
      const { data: res } = await this.$http.post("categories", this.addForm);
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.addCateVisible = false;
      this.getCateList();
    },
    // 选择分类
    handleChange() {
      // 将选择中的父类型的id设置到addform中的cate_pid
      // 还需要设置cate_level层级s
      if (this.selectedCateIds.length === 0) {
        // 没有选择父类别，表示添加的就是一级类别
        this.addForm.cat_level = 0;
        this.addForm.cat_pid = 0;
      } else {
        this.addForm.cat_level = this.selectedCateIds.length;
        this.addForm.cat_pid =
          this.selectedCateIds[this.selectedCateIds.length - 1];
      }
    },

    // 打开编辑类别对话框
    async showEdit(cates) {
      console.log(cates);
      this.editCateVisible = true;
      const { data: res } = await this.$http.get(`categories/${cates.cat_id}`);

      this.editForm = res.data;
    },
    // 关闭编辑分类对话框
    handleEditClose() {
      this.$refs.editForm.resetFields();
      this.editCateVisible = false;
    },
    // 编辑对话框确认
    editCatesInfo(id) {
      this.$resf.editForm.validate(async (result) => {
        if (result) {
          const { data: res } = await this.$http.put(
            `categories/${id}`,
            this.editForm
          );
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg);
          } else {
            this.$message.error(res.meta.msg);
            this.getCateList();
            this.editCateVisible = false;
          }
        }
      });
    },

    // 打开确认删除框
    open(cates) {
      // console.log(cates);
      this.$confirm(
        `此操作将永久删除该<span style="color:red;font-weight:bold;"> ${cates.cat_name} </span>分类, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          dangerouslyUseHTMLString: true,
          type: "warning",
        }
      )
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${cates.cat_id}`
          );
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.getCategoryList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "那就不删了奥",
          });
        });
    },
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin: 15px 0;
}
</style>